//
//  DBHelper.swift
//  MyProject
//
//  Created by volantPig on 2020/11/11.
//

import UIKit
import CoreData

class DBHelper: NSObject {
    static let `default` = DBHelper()
    
    // MARK: - CoreData - start
    lazy var managedObjectModel: NSManagedObjectModel = {
        let modelURL = Bundle.main.url(forResource: "MyProject", withExtension: "momd")
        let managedObjectModel = NSManagedObjectModel.init(contentsOf: modelURL!)
        return managedObjectModel!
    }()
    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
        let persistentStoreCoordinator = NSPersistentStoreCoordinator.init(managedObjectModel: managedObjectModel)
        let sqliteURL = documentDir.appendingPathComponent("MyProject.sqlite")
        let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
        do {
            try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: sqliteURL, options: options)
        } catch {
            abort()
        }
        return persistentStoreCoordinator
    }()
    lazy var context: NSManagedObjectContext = {
        let context = NSManagedObjectContext.init(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
        context.persistentStoreCoordinator = persistentStoreCoordinator
        return context
    }()
    lazy var documentDir: URL = {
        let documentDir = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first
        return documentDir!
    }()
    // MARK: - CoreData - end
    
    
    //  存储 用户信息
    func save(_ data: String?) {
        guard let confirmData = data else {
            return
        }
        DBManager.default.saveData(data: confirmData)
    }
    
    func getLastHistoryData() -> HistoryData? {
        let historyList = DBManager.default.getAllLocalData()
        if historyList.count > 0 {
            return historyList[0]
        }
        return nil
    }
}
